package com.sun.kamun.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sun.kamun.entity.Admin;
import com.sun.kamun.entity.User;
import com.sun.kamun.service.AdminService;

import javax.servlet.http.HttpSession;

import com.sun.kamun.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/admin")
@Slf4j
public class AdminController {
    @Autowired
    private AdminService adminService;

    @Autowired
    private UserService userService;


    /**
     * 管理员初始登录页面
     */
    @GetMapping("/login")
    public String login() {
        return "index";
    }


    /**
     * 与前端ajax请求对应,post登录
     */
    @PostMapping("/login")
    public String adminLogin(HttpSession session, @RequestParam String username, @RequestParam String password) {
        Admin admin = adminService.login(username, password);
        if (admin == null) {
            // 登录失败
            return "index";
        } else {
            // 登录成功，将管理员对象存储在 session 中
            session.setAttribute("admin", admin);
            // 设置过期时间为1小时
            session.setMaxInactiveInterval(60*60*24);// 设置过期时间为1*60*24分钟(登录状态1天失效)
            log.info("打开卡盟商城首页");
            return "redirect:/admin/home";
        }
    }


    /**
     * 后台管理页面
     */
    @GetMapping("/home")
    public String home() {
        return "home";
    }

    /**
     * 管理员---我的信息
     */
    @GetMapping("/info")
    public String getAdminInfo(HttpSession session, Model model) {
        // 从 HttpSession 获取当前登录用户的 adminId
        Admin admin= (Admin) session.getAttribute("admin");

        // 从 admin 对象中获取账号信息
        String adminName = admin.getAdminName();

        log.info("开始获取adminName的值: "+adminName);

        // 调用 Service 层方法获取当前登录用户的账号信息
        Admin adminInfo = adminService.selectAdminInfo(adminName);

        // 将账号信息存入 Model 中，在视图中进行展示
        model.addAttribute("adminId", adminInfo.getAdminId());
        model.addAttribute("adminName", adminInfo.getAdminName());
        model.addAttribute("adminPassword", adminInfo.getAdminPassword());

        // 返回视图名称
        return "admininfo";
    }

    /**
     * 管理员_注销当前账户登录
     * */
    @GetMapping("/logout")
    public String logout(HttpSession session){
        // 清空当前会话的相关信息
        session.invalidate();
        // 跳转到登录页或其他需要跳转的页面
        return "redirect:/admin/login";
    }

    /**
     * 管理员-查看会员列表
     *
     * @return*/
    @GetMapping("/users")
    public String getUserList(Model model){
        List<User> userList = userService.list(null);
        model.addAttribute("userList", userList);
        return "userlist";
    }

//    @GetMapping("/users")
//    public String getUserListPage(Model model,
//                              @RequestParam(defaultValue = "1") int page,
//                              @RequestParam(defaultValue = "10") int pageSize) {
//        Page<User> userPage = new Page<>(page, pageSize);
//        IPage<User> userPageResult = userService.page(userPage, null);
//
//        List<User> userList = userPageResult.getRecords();
//        model.addAttribute("userListPage", userList);
//        model.addAttribute("currentPage", userPageResult.getCurrent());
//        model.addAttribute("totalPages", userPageResult.getPages());
//        model.addAttribute("page",page);
//        model.addAttribute("pageSize",pageSize);
//
//        return "userlist";
//    }



    /**
     * 模糊查询用户列表
     * */
    @GetMapping(value = "/usersByCondition", produces = "text/html;charset=UTF-8")
    public String getUserListByCondition(@RequestParam String username, Model model) {
        List<User> userList;
        if (username != null && !username.isEmpty()) {
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            wrapper.like(User::getUserName,username);
            log.info("开始模糊查询");
            userList=userService.list(wrapper);
        } else {
            userList = userService.list(null);
        }
        model.addAttribute("userList", userList);
        return "userlist";
    }

    /**
     * 管理员_修改会员信息
     *这个是依赖视图弹窗实现的
     * @return*/
    @PutMapping(value = "/updateUser/{userId}", produces = "text/html;charset=UTF-8")
    public String updateUser(@PathVariable int userId, @RequestBody User updatedUser) {
        // 根据userId查询要修改的会员信息
        User user = userService.getById(userId);
        log.info("开始获取当前修改用户的id:"+userId);
        System.out.println(user);
        if (user == null) {
            // 未找到对应的会员，返回false表示修改失败
            return "error";
        }


        // 更新会员信息
        user.setUserRealname(updatedUser.getUserRealname());
        user.setUserPhone(updatedUser.getUserPhone());
        user.setUserEmail(updatedUser.getUserEmail());
        user.setUserScoreleft(updatedUser.getUserScoreleft());
        //获取当前系统时间并设置
        user.setUserUpdatetime(new Date());

        // 执行更新操作
        log.info("开始执行更新操作");
        boolean result = userService.updateById(user);

        if (result) {
            // 更新成功，返回用户列表视图
//            return "redirect:/admin/users";
//            model.addAttribute("updateUser",true);
            //这里更新成功就直接返回userlist.html界面了
            return "userlist";
        } else {
            // 更新失败，保持在原界面
//            model.addAttribute("updateUser",false);
            return "error"; // 或者返回原界面的视图名称
        }
    }


    /**
     * 管理员_删除用户信息
     * */
    @DeleteMapping("/{userId}")
    public String deleteUserById(@PathVariable int userId){
        //先进行查询,检测当前操作用户存不存在
        User user = userService.getById(userId);
        if(user == null){
            return "error";
        }else {
            userService.removeById(userId);
            return "userlist";
        }

    }

    /**
     * 管理员--新增会员信息
     * */
    @PostMapping(value = "/userAddByAdmin" ,produces = "text/html;charset=UTF-8")
    public String AddUserByAdmin(@RequestBody User userAdd){
        User user=new User();
        user.setUserName(userAdd.getUserName());
        user.setUserPassword(userAdd.getUserPassword());
        user.setUserRealname(userAdd.getUserRealname());
        user.setUserPhone(userAdd.getUserPhone());
        user.setUserEmail(userAdd.getUserEmail());
        user.setUserScoreleft(userAdd.getUserScoreleft());
        user.setUserCreatetime(new Date());
        user.setUserUpdatetime(new Date());
        boolean save = userService.save(user);
        if(save){
            return "userlist";
        }else {
            return "error";
        }
    }


    /**
     * 管理员---设置用户状态
     * */
    @PutMapping("/status/{userId}")
    public String changeUserStatus(@PathVariable int userId){
        //获取页面列表里的用户id,查询用户
        User user = userService.getById(userId);
        log.info("当前用户信息是: "+user);
        int status = user.getUserStatus();
        if(status == 0){
            user.setUserStatus(1);
        }else {
            user.setUserStatus(0);
        }
        userService.updateById(user);
        return "userlist";
    }
}
